package cn.edu.nchu.comic_strip.ui.collection;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.List;

import cn.edu.nchu.comic_strip.R;
import cn.edu.nchu.comic_strip.entity.Page;

public class CollectionBookDetailAdapter extends ArrayAdapter<Page> {
    private Context mContext;

    public CollectionBookDetailAdapter(Context context, List<Page> objects) {
        super(context, 0, objects);
        this.mContext = context;  // 初始化 mContext
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.collection_book_detail_item, parent, false);
        }

        Page page = getItem(position);

        if (page != null) {
            TextView pageText = convertView.findViewById(R.id.page_text);
            ImageView bookCover = convertView.findViewById(R.id.page_image);
            TextView charText = convertView.findViewById(R.id.chapter_number);

            charText.setText(page.getTitle());
            // 设置前30个字符，并用省略号代替超出部分
            String summary = page.getSummary();
            if (summary.length() > 30) {
                summary = summary.substring(0, 30) + "...";
            }
            pageText.setText(summary);

            // 解析资源名称字符串，获取对应的资源 ID
            int resourceId = mContext.getResources().getIdentifier(page.getImageResId(), "drawable", mContext.getPackageName());
            bookCover.setImageResource(resourceId);
        }

        return convertView;
    }
}
